﻿using CommonLib;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppConsumer2;

internal class TestDirectPattern
{
    private static readonly string QueueName = "direct-disk";
    private static readonly string ExchangeName = "direct-logs";

    /// <summary>
    /// Direct 路由模式
    /// </summary>
    public static void TestDirect()
    {
        // 1 创建 channel
        var channel = RabbitMQUtil.CreateChannel();

        // 2 声明交换机
        channel.ExchangeDeclare(ExchangeName, "direct", true, false, null);

        // 3 声明队列
        channel.QueueDeclare(QueueName, true, true, false, null);

        // 4 绑定队列到交换机
        channel.QueueBind(QueueName, ExchangeName, "error", null);

        //channel.BasicQos(1,1,false);

        // 5 回调函数
        var consumer = new AsyncEventingBasicConsumer(channel);
        consumer.Received += Consumer_Received;
        async Task Consumer_Received(object sender, BasicDeliverEventArgs args)
        {
            try
            {
                var bytes = args.Body.ToArray();
                var msg = Encoding.UTF8.GetString(bytes);
                Console.WriteLine("Consumer2 收到了消息：" + msg);
                channel.BasicAck(args.DeliveryTag, multiple: false);
                await Task.Delay(1000);
            }
            catch (Exception ex)
            {
                channel.BasicReject(args.DeliveryTag, true);
                Console.WriteLine("处理消息异常：" + ex.Message);
            }
        }

        // 6 消费消息
        channel.BasicConsume(QueueName, false, consumer: consumer);

        Console.ReadLine();
    }
}
